package cn.kgc.crowdfundingadmin2.controller;

import cn.kgc.crowdfundingadmin2.common.ResultEntity;
import cn.kgc.crowdfundingadmin2.pojo.Menu;
import cn.kgc.crowdfundingadmin2.service.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MenuController {

    @Resource
    MenuService menuService;

    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
        //所有菜单
        List<Menu> all = menuService.getAll();
        //把菜单集合转换成Map
        Map<Integer,Menu> map=new HashMap<>();
        for (Menu menu : all) {
            map.put(menu.getId(),menu);
        }

        //找到根节点
        Menu root=null;
        for (Menu menu : all) {
            if (menu.getPid()==null){
                root=menu;
                continue;
            }
            //pid不是null，要找到他的父节点，并封装到子节点集合中
            //menu  id 2 pid 1  控制面板 url  icon
            //从map中找到节点对象
            map.get(menu.getPid()).getChildren().add(menu);
        }

        return ResultEntity.successWithoutData(root);
    }

    @RequestMapping("/menu/save")
    public ResultEntity<String> save(Menu menu){
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/get/{menuId}")
    public ResultEntity<Menu> getMenuId(@PathVariable Integer menuId){
        Menu menu = menuService.getMenuById(menuId);
        return ResultEntity.successWithoutData(menu);
    }

    @RequestMapping("/menu/update")
    public ResultEntity<String> update(Menu menu){
        menuService.update(menu);
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/delete/{menuId}")
    public ResultEntity<String> delete(@PathVariable Integer menuId){
        menuService.delete(menuId);
        return ResultEntity.successWithoutData();
    }
}
